//
//  FindEmoticonString.swift
//  Status
//
//  Created by Kylin on 16/3/29.
//  Copyright © 2016年 Kylin. All rights reserved.
//

import UIKit

class FindEmoticonString {

    // 设计单例对象
    static let shareManager : FindEmoticonString = FindEmoticonString()
    
    // 懒加载属性
    private lazy var manager : EmoticonManager = EmoticonManager()
    
    func findEmoticonString(statusText : String,fontHeight :CGFloat) -> NSMutableAttributedString? {
        
        // 创建规则
        let pattern = "\\[.*?\\]"
        
        // 2.创建正则表达式对象
        guard let regex = try? NSRegularExpression(pattern: pattern, options: []) else {
            return nil
        }
        // 3.匹配结果
        let results = regex.matchesInString(statusText, options: [], range: NSRange(location: 0, length: statusText.characters.count))
        
        // 4.遍历结果
        // 4.0.根据原有内容创建可变的属性字符串
        let attrMStr = NSMutableAttributedString(string:statusText)
        // 从后往前遍历
        for var i = results.count - 1; i >= 0 ; i -= 1 {
            // 4.0.取出result

            let result = results[i]
            // 4.1.获取表情对应的chs
            let chs = (statusText as NSString).substringWithRange(result.range)
            // 4.2.根据chs查找pngPath
            guard let pngPath = findPngPathWithChs(chs) else {
                continue
            }
            
            // 4.3.创建属性字符串
            let attacment = NSTextAttachment()
            attacment.bounds = CGRect(x: 0, y: -3, width: fontHeight, height: fontHeight)
            attacment.image = UIImage(contentsOfFile: pngPath)
            let resultAttrStr = NSAttributedString(attachment: attacment)
            
            // 4.4.将之前的chs文字,替换成带图片的属性字符串
            attrMStr.replaceCharactersInRange(result.range, withAttributedString: resultAttrStr)
        }
        
        return attrMStr
    }
    private func findPngPathWithChs(chs :String) -> String? {
        for package in manager.packages{
            for emoticon in package.emoticons {
                if emoticon.chs == chs {
                    return emoticon.pngPath
                }
            }
        }
        return nil
    }
}
